package com.controller;

import com.Table.Movie;
import com.model.operation.MovieOperate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by LPFma on 2016/12/6 0006.
 */
@WebServlet(name = "Search", urlPatterns = "/Search")
public class Search extends HttpServlet {
    final int num = 10;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*init response*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

        String key = request.getParameter("moviename");
        String pages = request.getParameter("pages");

        MovieOperate movieOperate = new MovieOperate();
        ArrayList<Movie> movieArrayList =
                movieOperate.SearchVideo(key);

        JSONArray jsonArray = new JSONArray();
        for (Movie movie : movieArrayList) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("movieID", movie.getMovieID());
                jsonObject.put("moviename", movie.getMoviename());
                jsonObject.put("address", movie.getAddress());
                jsonObject.put("picture", movie.getPicture());
                jsonObject.put("tag", movie.getTag());
                jsonObject.put("descrition", movie.getDescription());
                jsonObject.put("coinnum", movie.getCoinnum());

                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        JSONObject jsonObjAmount = new JSONObject();
        try {
            int size = movieArrayList.size();
            jsonObjAmount.put("pages", Integer.valueOf(pages));
            jsonObjAmount.put("num", num);
            jsonObjAmount.put("totalnum", size);
            size = size % 10 == 0 ? size / 10 : size / 10 + 1;
            jsonObjAmount.put("totalpages", size);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObjAmount);
        response.getWriter().write(jsonArray.toString());
    }
}
